#include "useHead.h"
#include "stringTable.h"

size_t StringTable::add(const string &str)
{
	for (int i = 0; i < _vstring.size(); ++i)
		if (_vstring[i] == str)
			return i;

	_vstring.push_back(str);
	return _vstring.size() - 1;
}



int StringTable::readFile(FILE *fp)
{
#define FREAD(x, type)  nread = fread(&(x), sizeof(type), 1, fp);\
			if (nread != 1) { \
				fprintf(stderr, "Error! %s %s %d\n", __FILE__, __FUNCTION__, __LINE__); \
				return -1;\
			}
    int nread;
	int size, t;
	static char buf[1024*4];

	if (fp == NULL)
		return -1;

	FREAD(size, int);
	_vstring.resize(size);
	for (int i = 0; i < size; ++i) {
		FREAD(t, int);

		if (t >= sizeof(buf)) {
			printf("buf is not enough!");
		}

		nread = fread(buf, t, 1, fp);
        if (nread < 1)
            return -1;

		buf[t] = 0;
		_vstring[i] = buf;
	}

#undef FREAD
    return 0;
}


void StringTable::writeFile(FILE *fp)
{
	int size, t;

	if (fp == NULL)
		return;

	size = _vstring.size();
	fwrite(&size, sizeof(int), 1, fp);
	for (int i = 0; i < _vstring.size(); ++i) {
		t = _vstring[i].size();
		fwrite(&t, sizeof(t), 1, fp);
		fwrite(_vstring[i].c_str(), t, 1, fp);
	}
}


void StringTable::dump()
{
    puts("\n+++++++++++++++++<String Table Dump>++++++++++++++++++++++++\n");
	printf("String Number: %d\n\n", _vstring.size());
	for (int i = 0; i < _vstring.size(); ++i)
		printf("(%d).\"%s\"\n", i, _vstring[i].c_str());
	putchar('\n');
    puts("\n+++++++++++++++++<String Table Dump>++++++++++++++++++++++++\n");
}



